/**    
 * @{#} RequestTaskIntercept.java Create on 2014年8月29日 下午5:31:21    
 *    
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin.intercept;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;
import cn.o.app.json.JsonUtil;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.task.RequestTask;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

public class RequestTaskIntercept {

	/**
	 * 
	 * method desc：
	 * 
	 * @param context
	 * @param request
	 * @param handler
	 * @param params
	 */
	@SuppressWarnings("unchecked")
	public static void requestIntercept(final Context context, String request,
			RequestHandler handler, HashMap<String, Object> params) {
		if (params.containsKey(Constant.PARAM_TOKEN)
				&& CommonUtility.isNull(params.get(Constant.PARAM_TOKEN))) {
			// DialogExt dialog = CommonUtility.tip(context, "当前会话已失效，请重新登陆。");
			// dialog.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View view) {
			// // TODO Auto-generated method stub
			// CommonUtility.finish();
			// context.startActivity(new Intent(context,
			// LoginActivity.class));
			// }
			// });
			
			Log.i("testlogin", "requestIntercept.if");
			
			reAutoLogin(context, request, handler, true, params);
			
			Log.i("testlogin", "request:" + request.toString());
			
		} else {
			
			Log.i("testlogin", "requestIntercept.else");
			Log.i("testlogin", "request:" + request.toString());
			new RequestTask(context, request, handler).execute(params);
		}
	}

	/**
	 * 当请求包含token时，判断token是否为空，为空则自动重新登陆 method desc：
	 * 
	 * @param context
	 * @param request
	 * @param handler
	 * @param isShowDialog
	 * @param requestParams
	 */
	static void reAutoLogin(Context context, String request, Handler handler,
			boolean isShowDialog, HashMap<String, Object> requestParams) {
		SharedPreferences preferences = CommonUtility
				.getSharedPreferences(context);
		int loginType = preferences
				.getInt(Constant.IDENTITY_KEY_LOGIN_TYPE, -1);
		if (loginType != -1) {
			HashMap<String, Object> p = new HashMap<String, Object>();
			String username = preferences.getString(
					Constant.IDENTITY_KEY_LOGIN_USERNAME, null);
			String password = preferences.getString(
					Constant.IDENTITY_KEY_LOGIN_PASSWORD, null);
			if (loginType == GlobalSettings.LOGIN_TYPE_USERNAME) {
				p.put(Constant.PARAM_API, "User.Login");
				p.put("mobile", username);
				p.put("pwd", password);
			} else if (loginType == GlobalSettings.LOGIN_TYPE_THIRD) {
				p.put(Constant.PARAM_API, "User.ThirdLogin");
				p.put("third_type", username);
				p.put("third_id", password);
			}
			
			Log.i("testlogin", "reAutoLogin.login");
			
			
			login(context, p, request, handler, isShowDialog, requestParams);
		}
	}

	static void login(final Context context, final HashMap<String, Object> p,
			final String request, final Handler handler,
			final boolean isShowDialog,
			final HashMap<String, Object> requestParams) {
		RequestTaskIntercept.requestIntercept(context, Constant.URL.REQUEST,
				new RequestHandler(context, new HandlerCallback() {
					@Override
					public void callback(Object o) {
						// TODO Auto-generated method stub
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							if (CommonUtility.response200(object)) {
								try {
									object = CommonUtility.responseRes(object);
									GlobalSettings.sToken = object
											.getString(Constant.JSON_PARAM_TOKEN);
									GlobalSettings.sUid = object
											.getInt(Constant.PARAM_UID);
									RequestTaskIntercept.requestIntercept(
											context,
											Constant.URL.REQUEST,
											new RequestHandler(context,
													new HandlerCallback() {

														@SuppressWarnings("unchecked")
														@Override
														public void callback(
																Object o) {
															if (!CommonUtility
																	.isNull(o)) {
																try {
																	JSONObject object = (JSONObject) o;
																	JSONArray array = object
																			.getJSONArray(Constant.JSON_PARAM_RES);
																	if (array
																			.length() > 0) {
																		GlobalSettings.sUser = JsonUtil
																				.convertFromObject(
																						array.getJSONObject(0),
																						User.class);
																		Intent intent = new Intent(
																				Constant.RECIVER_QUESTION);
																		intent.putExtra(
																				Constant.IDENTITY_KEY_USER_TYPE,
																				1);
																		((Activity) context)
																				.sendBroadcast(intent);
																		new RequestTask(
																				context,
																				request,
																				handler,
																				isShowDialog)
																				.execute(requestParams);
																	}
																} catch (Exception e) {
																	e.printStackTrace();
																}
															}
														}
													}),
											CommonUtility
													.params(new String[] {
															Constant.PARAM_API,
															"uids" },
															new Object[] {
																	"User.Get",
																	GlobalSettings.sUid }));
								} catch (Exception e) {
									// TODO: handle exception
									e.printStackTrace();
								}
							} else {
								CommonUtility.toast(context,
										CommonUtility.info(object));
							}
						}
					}
				}), p);
	}

	/**
	 * 
	 * method desc：
	 * 
	 * @param context
	 * @param request
	 * @param handler
	 * @param isShowDialog
	 * @param params
	 */
	@SuppressWarnings("unchecked")
	public static void requestIntercept(final Context context, String request,
			RequestHandler handler, boolean isShowDialog,
			HashMap<String, Object> params) {
		if (params.containsKey(Constant.PARAM_TOKEN)
				&& CommonUtility.isNull(params.get(Constant.PARAM_TOKEN))
				&& context instanceof Activity) {
			// DialogExt dialog = CommonUtility.tip(context, "当前会话已失效，请重新登陆。");
			// dialog.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View view) {
			// // TODO Auto-generated method stub
			// CommonUtility.finish();
			// context.startActivity(new Intent(context,
			// LoginActivity.class));
			// }
			// });
			reAutoLogin(context, request, handler, isShowDialog, params);
		} else {
			new RequestTask(context, request, handler, isShowDialog)
					.execute(params);
		}
	}
}
